#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "thread.h"


struct tableau{
  int debut;
  int fin;
  int * pointeur;
};

void * somme_tab(struct tableau * tabx){
  thread_t thread1, thread2;
  
  int result1 = 0;
  int result2 = 0;
  
  if (tabx->debut == tabx->fin){
   thread_exit((void *)tabx->debut);  
  }
  
  else {
  	
    struct tableau * tab1 = malloc(sizeof(struct tableau));
    struct tableau * tab2 = malloc(sizeof(struct tableau));
    
    tab1->debut = tabx->debut;
    tab1->fin = (tabx->debut + tabx->fin)/2;
    tab1->pointeur= malloc(sizeof(int));
    tab1->pointeur= tabx->pointeur;
    
    tab2->debut = (tabx->debut + tabx->fin)/2 + 1;
    tab2->fin = tabx->fin;
    tab2->pointeur= malloc(sizeof(int));
    tab2->pointeur=tabx->pointeur;
    
    thread_create(&thread1, somme_tab,tab1);
    thread_create(&thread2,  somme_tab, tab2);
    
    thread_join(thread1, &result1);
    thread_join(thread2, &result2);
    
    int a = result1+result2 ;
    
    thread_exit(&a);
  }
}

int main(int argc, char * argv[]){
  int taille = 9;
    
  clock_t start, end;
  start = clock ();
  {
    printf("Veuillez choisir un argument pour la fonction somme :\n");
    scanf("%d",&taille);
    printf("Vous avez choisi le nombre : %d\n", taille);
  
    int i =0 ;
    int j= 0;
 
    int * t= malloc(taille*sizeof(int));
  
    for(i = 0; i < taille; i++){
      t[i] = 1;
    }
    
    struct tableau * tab=malloc(sizeof(struct tableau));
  
    thread_t thread;
  
    int result;
    result = 0;
  
    tab->pointeur = malloc(sizeof(int));
    tab->pointeur=t;
    tab->debut = j;
    tab->fin = taille;
  
    if(!(&thread)) printf("######!\n");
  
    thread_create(&thread,  somme_tab, tab);
    thread_join(thread, & result);
  }
  end = clock ();
  
  printf ("Temps en secondes : %f\n", (end - start) / (double)CLOCKS_PER_SEC);
  
  return EXIT_SUCCESS;
  
}
